﻿<!DOCTYPE html>

<html lang="zh-cn" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width,initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no" />
    <title>书签管理</title>
    <link href="/lib/bootstrap/dist/css/bootstrap.css" rel="stylesheet" />
    <style type="text/css">
    </style>
</head>
<body style="background-color:#f0f0f0;">
    <div style="max-width:1000px;margin:0 auto;padding:20px;">
        <div style="line-height: 50px;display:flex;">
            <div style="flex: 1; text-align: left;">
                <a class="btn btn-default" href="javascript:void(0);" onclick="reload_data(this)">
                    <span class="glyphicon glyphicon-refresh" aria-hidden="true"></span>
                    <span>刷新</span>
                </a>
                <a class="btn btn-default" href="javascript:void(0);" onclick="refresh(this)">
                    <span class="glyphicon glyphicon-flag" aria-hidden="true"></span>
                    <span>检测书签状态（同时更新书签信息）</span>
                </a>
                <a class="btn btn-warning" href="javascript:void(0);" onclick="reset(this)">
                    <span class="glyphicon glyphicon-tag" aria-hidden="true"></span>
                    <span>重置书签状态</span>
                </a>
                <a class="btn btn-warning" href="javascript:void(0);" onclick="del_duplicate(this)">
                    <span class="glyphicon glyphicon-leaf" aria-hidden="true"></span>
                    <span>去重</span>
                </a>
                <a class="btn btn-danger" href="javascript:void(0);" onclick="del_many(this)">
                    <span class="glyphicon glyphicon-remove" aria-hidden="true"></span>
                    <span>删除选中</span>
                </a>
                <a class="btn btn-danger" href="javascript:void(0);" onclick="del_invalids(this)">
                    <span class="glyphicon glyphicon-remove" aria-hidden="true"></span>
                    <span>删除无效书签</span>
                </a>
            </div>
            <div style="width:160px;text-align:right;">
                <a class="btn btn-default" style="position:relative;display:inline-block;overflow:hidden;" href="javascript:void(0);">
                    <span class="glyphicon glyphicon-import" aria-hidden="true"></span>
                    <span>导入</span>
                    <input type="file" style="position:absolute;top:0;right:0;opacity:0;" onchange="file_changed(this);">
                </a>
                <a class="btn btn-default" href="javascript:void(0);" onclick="export_all(this)">
                    <span class="glyphicon glyphicon-export" aria-hidden="true"></span>
                    <span>导出</span>
                </a>
            </div>
        </div>
        <div style="border: 1px solid #ccc; background-color: #fff; box-shadow: 0 0 3px #ccc; ">
            <div style="display: flex; min-height: 40px; line-height: 40px; background-color: #f0f0f0; border-bottom: 2px solid #ccc;">
                <div style="width:40px;text-align:center;"><input type="checkbox" onclick="choose_all(this)" /></div>
                <div style="width:40px;text-align:center;border-left:1px solid #ccc;">图标</div>
                <div style="width:300px;border-left:1px solid #ccc;padding:0 10px;">标题</div>
                <div style="width:350px;border-left:1px solid #ccc;padding:0 10px;">网址</div>
                <div style="width:60px;border-left:1px solid #ccc;text-align:center;">状态</div>
                <div style="flex:1;border-left:1px solid #ccc;padding:0 10px;">操作</div>
            </div>
        </div>
        <div id="_div_result" style="min-height: 420px; border: 1px solid #ccc; background-color: #fff; box-shadow: 0 0 3px #ccc; overflow-y: auto;"></div>
        <div id="_div_total" style="min-height:40px;line-height:40px;"></div>
    </div>
    <script src="/lib/jquery/dist/jquery.js"></script>
    <script>
        $(function () {
            $('#_div_result').css('height', (document.documentElement.clientHeight - 180) + 'px');
            load_data();
        });
    </script>
    <script>
        function file_changed(sender) {
            if (sender.files.length === 0) {
                master.show_toast("请选择文件");
                return;
            }

            var file1 = sender.files[0];
            var filename = file1.name;
            var fileext = filename.substr(filename.lastIndexOf(".")).toLowerCase();
            var uploadexts = '.html';
            var idx = uploadexts.indexOf(fileext);
            if (idx < 0) {
                master.show_toast("不支持的格式，只支持" + uploadexts + "，当前文件格式：" + fileext);
                return;
            }

            var maxfilesize = 1024;
            var kbsize = 1.0 * file1.size / 1024;
            if (kbsize > maxfilesize) {
                master.show_toast("很抱歉，最多只能上传" + maxfilesize + "KB大小的文件,当前文件大小:" + kbsize + "KB");
                return;
            };

            var reader1 = new FileReader();
            reader1.readAsDataURL(file1);
            reader1.onload = function (e) {
                var filedata = e.target.result;
                upload(filename, filedata);
            };
        }

        function upload(filename, filedata) {
            $.ajax({
                url: '/import',
                type: 'POST',
                data: { filename, filedata },
                complete: function (xhr, status) {
                    var msg = '导入失败，请稍后再试';
                    if (status != "success") {
                        master.show_toast(msg);
                        return;
                    }

                    var rsp;
                    try {
                        rsp = JSON.parse(xhr.responseText);
                    } catch (e) {
                    }

                    if (rsp && rsp.error_message) {
                        msg = rsp.error_message;
                    }

                    if (rsp && rsp.data) {
                        master.show_toast(rsp.data);
                        load_data();
                        return;
                    }

                    master.show_toast(msg);
                }
            });
        }

        var page_data = {
            page: 1,
            pageSize: 20
        };
        function load_data(callback) {
            $.ajax({
                url: '/list',
                type: 'POST',
                data: page_data,
                complete: function (xhr, status) {
                    var msg = '加载失败，请稍后再试';
                    if (status != "success") {
                        master.show_toast(msg);
                        return;
                    }

                    var rsp;
                    try {
                        rsp = JSON.parse(xhr.responseText);
                    } catch (e) {
                    }

                    if (rsp && rsp.error_message) {
                        msg = rsp.error_message;
                    }

                    var total = 0;
                    if (rsp && rsp.data) {
                        total = rsp.data.length;
                        var sb = '';
                        for (var i = 0; i < rsp.data.length; i++) {
                            var item = rsp.data[i];
                            var status = '<span>未检测</span>';
                            if (item.Status) {
                                switch (item.Status) {
                                    case 1: {
                                        status = '<span style="color:#ff7f27;">检测中</span>';
                                        break;
                                    }
                                    case 2: {
                                        status = '<span style="color:#22b14c;">有效</span>';
                                        break;
                                    }
                                    case 3: {
                                        status = '<span style="color:#ed1c24;">无效</span>';
                                        break;
                                    }
                                }
                            }
                            var background = '';
                            if (i % 2 == 1) {
                                background = 'background-color:#f0f0f0;';
                            }
                            var icon = '<img style="width:24px;width:24px;" src="no-icon" />';
                            if (item.Icon) {
                                icon = '<img style="width:24px;width:24px;" src="' + item.Icon + '" />';
                            }
                            var title = item.Title;
                            if (get_real_length(title) > 30) {
                                title = sub_real_length(title, 30) + '...';
                            }
                            var url = item.Url;
                            if (get_real_length(url) > 40) {
                                url = sub_real_length(url, 40) + '...';
                            }
                            sb += '<div style="display:flex;min-height:40px;line-height:40px;' + background + 'border-bottom:1px solid #ccc;" onmouseenter="item_mouseenter(this)" onmouseleave="item_mouseleave(this)">';
                            sb += '<div style="width:40px;text-align:center;"><input type="checkbox" class="choose_one" data-id="' + item.Id + '" /></div>';
                            sb += '<div style="width:40px;text-align:center;border-left:1px solid #ccc;">' + icon + '</div>';
                            sb += '<div style="width:300px;border-left:1px solid #ccc;padding:0 10px;" title="' + item.Title + '">' + title + '</div>';
                            sb += '<div style="width:350px;border-left:1px solid #ccc;padding:0 10px;" title="' + item.Url + '">' + url + '</div>';
                            sb += '<div style="width:60px;border-left:1px solid #ccc;text-align:center;">' + status + '</div>';
                            sb += '<div style="flex:1;border-left:1px solid #ccc;padding:0 10px;">';
                            sb += '<div style="display:none;" class="item_operations">';
                            sb += '<a style="color:#ed1c24;" href="javascript:void(0)" onclick="del_one(this)" data-title="' + item.Title + '" data-url="' + item.Url + '" data-id="' + item.Id + '">删除</a>';
                            sb += '</div>';
                            sb += '</div>';
                            sb += '</div>';
                        }

                        $('#_div_result').html(sb);
                        $('#_div_total').html('共 ' + total + ' 个书签');
                        callback && callback();
                        return;
                    }

                    master.show_toast(msg);
                }
            });
        }

        function reload_data(sender) {
            load_data(function () {
                master.show_toast('刷新成功');
            });
        }

        var _item_background;

        var _item_cursor;

        function item_mouseenter(sender) {
            _item_background = sender.style.backgroundColor;
            _item_cursor = sender.style.cursor;
            sender.style.backgroundColor = '#f0f0f0';
            sender.style.cursor = 'pointer';

            var el = $(sender).find('.item_operations');
            if (el) {
                $(el).show();
            } 
        }

        function item_mouseleave(sender) {
            sender.style.backgroundColor = _item_background;
            sender.style.cursor = _item_cursor;

            var el = $(sender).find('.item_operations');
            if (el) {
                $(el).hide();
            }
        }

        function get_real_length(input) {
            var sum = 0;
            if (input) {
                for (var i = 0; i < input.length; i++) {
                    var ch = input.charCodeAt(i);
                    if (ch <= 255) {
                        sum += 1;
                    } else {
                        sum += 2;
                    }
                }
            }
            return sum;
        }

        function sub_real_length(input, num) {
            var input_sub = '';
            var sum = 0;
            if (input) {
                for (var i = 0; i < input.length; i++) {
                    var ch = input.charCodeAt(i);
                    if (ch <= 255) {
                        sum += 1;
                    } else {
                        sum += 2;
                    }
                    if (sum < num)
                    {
                        input_sub += input[i];
                    }
                }
            }
            return input_sub;
        }

        function choose_all(sender) {
            var items = document.getElementsByClassName('choose_one');
            for (var i = 0; i < items.length; i++) {
                items[i]['checked'] = sender['checked'];
            }
        }

        var master = {
            show_toast: function (msg, bgColor, color, ms) {
                if (!bgColor) {
                    bgColor = '#22b14c';
                }

                if (!color) {
                    color = '#fff';
                }

                if (ms == null) {
                    ms = 1500;
                }

                var el_id = "_div_toast_container";
                var el = document.getElementById(el_id);
                if (!el) {
                    el = document.createElement('div');
                    el.setAttribute('id', el_id);
                    el.style.width = '300px';
                    el.style.height = '400px';
                    el.style.position = 'fixed';
                    el.style.left = '50%';
                    el.style.top = '50%';
                    el.style.marginLeft = '-150px';
                    el.style.marginTop = '-200px';
                    el.style.overflow = 'hidden';
                    document.body.appendChild(el);
                }

                el.style.display = 'block';
                var toast_id = '_div_toast_' + new Date().getTime() + Math.floor(1000000 * Math.random());
                var sb = '';
                sb += '<div id="' + toast_id + '" style="text-align:center;margin-bottom:10px;"><span style="display:inline-block;box-shadow:0 0 2px #000;padding:10px 20px;border-radius:8px;background-color:' + bgColor + ';color:' + color + ';">' + msg + '</span></div>';
                $(el).append(sb);

                if (ms > 0) {
                    setTimeout(function () {
                        $('#' + toast_id).remove();
                    }, ms);
                }
            }
        };

        function get_selected_ids() {
            var ids = [];
            var items = document.getElementsByClassName('choose_one');
            for (var i = 0; i < items.length; i++) {
                if (items[i]['checked']) {
                    var id = $(items[i]).attr('data-id');
                    ids.push(id);
                }
            }
            return ids;
        }

        function del_one(sender) {
            var title = $(sender).attr('data-title');
            var url = $(sender).attr('data-url');
            if (!confirm('确定要删除 【' + title + '】【' + url + '】 吗')) {
                return;
            }

            var id = $(sender).attr('data-id');
            del_real(id);
        }

        function del_many(sender) {
            var ids = get_selected_ids();
            if (ids.length == 0) {
                master.show_toast('请选择要删除的书签');
                return;
            }

            if (!confirm('确定要删除选中的' + ids.length + '个书签吗')) {
                return;
            }

            del_real(ids.join(','));
        }

        function del_real(ids) {
            $.ajax({
                url: '/del',
                type: 'POST',
                data: { ids },
                complete: function (xhr, status) {
                    var msg = '删除失败，请稍后再试';
                    if (status != "success") {
                        master.show_toast(msg);
                        return;
                    }

                    var rsp;
                    try {
                        rsp = JSON.parse(xhr.responseText);
                    } catch (e) {
                    }

                    if (rsp && rsp.error_message) {
                        msg = rsp.error_message;
                    }

                    if (rsp && rsp.data) {
                        master.show_toast(rsp.data);
                        load_data();
                        return;
                    }

                    master.show_toast(msg);
                }
            });
        }

        function del_invalids() {
            var ids = get_selected_ids();
            if (ids.length == 0) {
                if (!confirm('未选择书签，将删除全部无效的书签，是否继续')) {
                    return;
                }
            }

            $.ajax({
                url: '/delinvalids',
                type: 'POST',
                data: { ids: ids.join(',') },
                complete: function (xhr, status) {
                    var msg = '删除失败，请稍后再试';
                    if (status != "success") {
                        master.show_toast(msg);
                        return;
                    }

                    var rsp;
                    try {
                        rsp = JSON.parse(xhr.responseText);
                    } catch (e) {
                    }

                    if (rsp && rsp.error_message) {
                        msg = rsp.error_message;
                    }

                    if (rsp && rsp.data) {
                        master.show_toast(rsp.data);
                        load_data();
                        return;
                    }

                    master.show_toast(msg);
                }
            });
        }
        
        function del_duplicate() {
            if (!confirm('将删除重复的书签，是否继续')) {
                return;
            }

            $.ajax({
                url: '/delduplicate',
                type: 'POST',
                data: { },
                complete: function (xhr, status) {
                    var msg = '去重失败，请稍后再试';
                    if (status != "success") {
                        master.show_toast(msg);
                        return;
                    }

                    var rsp;
                    try {
                        rsp = JSON.parse(xhr.responseText);
                    } catch (e) {
                    }

                    if (rsp && rsp.error_message) {
                        msg = rsp.error_message;
                    }

                    if (rsp && rsp.data) {
                        master.show_toast(rsp.data);
                        load_data();
                        return;
                    }

                    master.show_toast(msg);
                }
            });
        }

        function refresh() {
            var ids = get_selected_ids();
            if (ids.length == 0) {
                if (!confirm('未选择书签，将检测全部的书签状态，是否继续')) {
                    return;
                }
            }

            $.ajax({
                url: '/refresh',
                type: 'POST',
                data: { ids: ids.join(',') },
                complete: function (xhr, status) {
                    var msg = '操作失败，请稍后再试';
                    if (status != "success") {
                        master.show_toast(msg);
                        return;
                    }

                    var rsp;
                    try {
                        rsp = JSON.parse(xhr.responseText);
                    } catch (e) {
                    }

                    if (rsp && rsp.error_message) {
                        msg = rsp.error_message;
                    }

                    if (rsp && rsp.data) {
                        master.show_toast(rsp.data);
                        load_data();
                        return;
                    }

                    master.show_toast(msg);
                }
            });
        }

        function reset() {
            var ids = get_selected_ids();
            if (ids.length == 0) {
                if (!confirm('未选择书签，将重置全部的书签状态，是否继续')) {
                    return;
                }
            }

            $.ajax({
                url: '/reset',
                type: 'POST',
                data: { ids: ids.join(',') },
                complete: function (xhr, status) {
                    var msg = '操作失败，请稍后再试';
                    if (status != "success") {
                        master.show_toast(msg);
                        return;
                    }

                    var rsp;
                    try {
                        rsp = JSON.parse(xhr.responseText);
                    } catch (e) {
                    }

                    if (rsp && rsp.error_message) {
                        msg = rsp.error_message;
                    }

                    if (rsp && rsp.data) {
                        master.show_toast(rsp.data);
                        load_data();
                        return;
                    }

                    master.show_toast(msg);
                }
            });
        }

        function export_all() {
            $.ajax({
                url: '/export',
                type: 'POST',
                data: { },
                complete: function (xhr, status) {
                    var msg = '导出失败，请稍后再试';
                    if (status != "success") {
                        master.show_toast(msg);
                        return;
                    }

                    var rsp;
                    try {
                        rsp = JSON.parse(xhr.responseText);
                    } catch (e) {
                    }

                    if (rsp && rsp.error_message) {
                        msg = rsp.error_message;
                    }

                    if (rsp && rsp.data) {
                        var url = '/download?Module=' + rsp.data.Module + '&FileName=' + rsp.data.FileName;
                        window.open(url, '_blank');
                        return;
                    }

                    master.show_toast(msg);
                }
            });
        }
    </script>
</body>
</html>